<script setup lang="ts">
import type { EntityViewInfo, ModelInfo } from "@@/apis/entity/type"
import { deleteEntityModelApi, getEntityInfoApi } from "@@/apis/entity"
import { useThreeJs } from "@@/composables/useThreeJs"
import { FormTypeEnum } from "@@/constants/other-keys"
import { ElMessageBox } from "element-plus"
import { isEmpty, size } from "lodash-es"
import { nextTick, onActivated, onMounted, ref } from "vue"
import { useRoute } from "vue-router"
import EditBasicInfo from "./components/EditBasicInfo.vue"
import fileList from "./components/fileList.vue"
import EditModel from "./components/EditModel.vue"

defineOptions({
  name: "EntityView"
})

const fileVisible = ref<boolean>(false)
const route = useRoute()
const isEdit = ref<boolean>(false)
const currentId = ref<string>(route.query.id as string)
const entityInfo = ref<EntityViewInfo>()
const modelItems = ref<ModelInfo[]>([])
const editBasicInfoRef = ref()
const basicVisible = ref<boolean>(false)
const modelId = ref<string>()
const modelVisible = ref<boolean>(false)
const modelDialogType = ref<FormTypeEnum>(FormTypeEnum.CREATE)
const loading = ref<boolean>(false)
const three3DRef = ref<HTMLDivElement | null>(null)
const three3DModel = ref<ReturnType<typeof useThreeJs> | null>(null) // 修改类型定义
const modelInitialized = ref(false) // 添加初始化标志
const scrollBox = ref() // 添加初始化标志

// 添加模型加载状态和进度
const modelLoading = ref<boolean>(false)
const modelLoadingProgress = ref<number>(0)
const showThumbnail = ref<boolean>(true)
const thumbnailUrl = ref<string>('')
// 文件名称
const allFiles = ref<any>([
  '文档A.docx',
  '报告B.pdf',
  '图片C.png1111111111111',
  '合同D.doc',
  '演示E.pptx',
  '统计F.xlsx',
  '数据G.json',
  '数据G.json',
  '数据G.json',
  '数据G.json',
  '数据G.json',
  '数据G.json',
  '数据G.json',
  '数据G.jso11',
])
const wrapper = ref<any>(null)
const visibleFiles = ref<string[]>([])
const hiddenFiles = ref<string[]>([])
const fileData = ref([])

const calculateVisible = async () => {
  await nextTick()
  const containerWidth = wrapper.value.offsetWidth
  let currentWidth = 0
  const visible = []
  const hidden = []

  const tester = document.createElement('span')
  tester.style.visibility = 'hidden'
  tester.style.position = 'absolute'
  tester.style.whiteSpace = 'nowrap'
  tester.style.fontSize = '14px'
  tester.style.padding = '0 8px'
  document.body.appendChild(tester)

  for (let file of allFiles.value) {
    tester.innerText = file
    const width = tester.offsetWidth + 12 // margin
    if (currentWidth + width < containerWidth - 60) {
      visible.push(file)
      currentWidth += width
    } else {
      hidden.push(file)
    }
  }

  document.body.removeChild(tester)
  visibleFiles.value = visible
  hiddenFiles.value = hidden
}
const openFile = (val: any) => {
  window.open('/hubeihuanjing.pdf')
}

// 新增模型
function handleAddModel() {
  modelDialogType.value = FormTypeEnum.CREATE
  modelId.value = undefined
  modelVisible.value = true
}
// 查看模型
function handleViewModel(data: ModelInfo) {
  modelDialogType.value = FormTypeEnum.VIEW
  modelId.value = data.id
  modelVisible.value = true
}

// 激活编辑
function handleEdit() {
  isEdit.value = true
  basicVisible.value = true
}
const fileCloseDialog = () => {
  fileVisible.value = false
  getEntityInfo()
}

const imageUrl = ref()
function getEntityInfo() {
  loading.value = true
  getEntityInfoApi(currentId.value)
    .then(async ({ data }) => {
      modelItems.value = data.typings
      entityInfo.value = data
      imageUrl.value = data.entity.milstdPath
      // 设置缩略图URL
      thumbnailUrl.value = data.entity.threeThumbPath || ''
      showThumbnail.value = !isEmpty(thumbnailUrl.value)

      // 处理tag字段
      if (typeof entityInfo.value.entity.tag === 'string') {
        try {
          const parsedTag = JSON.parse(entityInfo.value.entity.tag as string)
          entityInfo.value.entity.tag = Array.isArray(parsedTag) ? parsedTag.join() : parsedTag
        } catch (e) {
          // 如果解析失败，保持原样
          console.error('解析tag字段失败', e)
        }
      }

      if (!modelInitialized.value) {
        await initThreeJs()
      }

      // 重置加载状态
      modelLoading.value = true
      modelLoadingProgress.value = 0

      // 注册进度回调并更新模型URL
      if (three3DModel.value) {
        three3DModel.value.setProgressCallback((progress: number) => {
          modelLoadingProgress.value = Math.round(progress * 100)
          if (progress >= 1) {
            setTimeout(() => {
              modelLoading.value = false
              showThumbnail.value = false
            }, 200)
          }
        });
        three3DModel.value.updateModelUrl(entityInfo.value?.entity.threePath)
      }
      fileData.value = data.files
    })
    .catch(() => {
      // modelItems.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

// 删除模型
function handleDeleteModel(data: ModelInfo) {
  ElMessageBox.confirm(`正在删除模型：${data.label}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    data.id && deleteEntityModelApi([data.id]).then(() => {
      getEntityInfo()
    })
  })
}

// 返回
// function handleBack() {
//   closeRoute()
//   router.back()
// }

function closeDialog() {
  basicVisible.value = false
  isEdit.value = false
  getEntityInfo()
}

function modelCloseDialog() {
  modelId.value = undefined
  modelVisible.value = false
  getEntityInfo()
}

async function initThreeJs() {
  return new Promise((resolve) => {
    nextTick(() => {
      if (isEmpty(three3DModel.value) && !isEmpty(entityInfo.value?.entity.threePath)) {
        try {
          // 打印模型路径和类型
          const modelPath = entityInfo.value?.entity.threePath || "";
          const extension = modelPath.toLowerCase().split('.').pop() || '';
          // 初始化模型查看器，但不立即加载模型（稍后通过updateModelUrl加载）
          three3DRef.value && (three3DModel.value = useThreeJs(three3DRef, undefined))
          modelInitialized.value = true
          resolve(true)
        } catch (error) {
          console.error("模型加载失败", error);
          modelLoading.value = false
          resolve(false)
        }
      } else {
        resolve(true)
      }
    })
  })
}

function handleScroll(event: { deltaY: any }) {
  let scrollNum = scrollBox.value
  // deltaY属性在向下滚动时返回正值，向上滚动时返回负值，否则为0
  scrollNum.scrollLeft = scrollNum.scrollLeft + event.deltaY
}
const fileClick = () => {
  fileVisible.value = !fileVisible.value
}

onMounted(() => {
  getEntityInfo()
  initThreeJs()
  calculateVisible()
  window.addEventListener('resize', calculateVisible)
})
onActivated(() => {
  if (currentId.value && currentId.value !== route.query.id) {
    currentId.value = route.query.id as string
    getEntityInfo()
  }
})
</script>

<template>
  <div v-loading="loading" class="app-container">
    <div class="entity-detail-container">
      <el-row class="top">
        <el-col :span="11">
          <div class="cpi-header">
            <span class="cpi-header-text">基本信息</span>
          </div>
          <el-row :gutter="20" style="padding: 0 10px;">
            <div class="ellipse item-border">
              <span class="entity-detail-content-info-item-label">名称</span>
              <span class="entity-detail-content-info-item-value"
                :title="`${entityInfo?.entity.code}（${entityInfo?.entity.name}）`">
                {{ entityInfo?.entity.code }}（{{ entityInfo?.entity.name }}）
              </span>
            </div>
            <div justify="start" class="item-border">
              <span class="entity-detail-content-info-item-label">标签</span>
              <span class="entity-detail-content-info-item-value" v-if="entityInfo?.entity?.tag !== 'null'">
                {{ entityInfo?.entity.tag }}
              </span>
            </div>
            <div justify="start" class="item-border">
              <span class="entity-detail-content-info-item-label">描述</span>
              <span class="entity-detail-content-info-item-value-description" :title="entityInfo?.entity.description">
                {{ entityInfo?.entity.description }}
              </span>
            </div>
          </el-row>
          <div style="margin-top: 5px;cursor: pointer;" @click.stop="fileClick">
            <SvgIcon name="fujian" style="display: inline-block;text-align: center;width: 60px;" :size="6" />
            <span style="display: inline-block;width: 100%;font-size: 14px;margin-top: 10px;">查看附件</span>
          </div>
        </el-col>
        <el-col :span="13">
          <div class="cpi-header">
            <span class="cpi-header-text">七类码</span>
            <el-button plain @click="handleEdit()">
              <el-icon>
                <Edit />
              </el-icon> 编辑
            </el-button>
          </div>
          <el-space :size="0" class="edc-sevencode" fill wrap :fill-ratio="25">
            <div class="ellipse item">
              <span class="entity-detail-content-info-item-label">平台</span>
              <span class="entity-detail-content-info-item-value" :title="entityInfo?.entityTypeText.kind">{{
                entityInfo?.entityTypeText.kind }}</span>
            </div>
            <div class="ellipse item">
              <span class="entity-detail-content-info-item-label">类型</span>
              <span class="entity-detail-content-info-item-value" :title="entityInfo?.entityTypeText.domain">{{
                entityInfo?.entityTypeText.domain }}</span>
            </div>
            <div class="ellipse item">
              <span class="entity-detail-content-info-item-label">国家地区</span>
              <span class="entity-detail-content-info-item-value" :title="entityInfo?.entityTypeText.country">{{
                entityInfo?.entityTypeText.country }}</span>
            </div>
            <div class="ellipse item">
              <span class="entity-detail-content-info-item-label">分类</span>
              <span class="entity-detail-content-info-item-value" :title="entityInfo?.entityTypeText.category">{{
                entityInfo?.entityTypeText.category }}</span>
            </div>
            <div class="ellipse item">
              <span class="entity-detail-content-info-item-label">子类</span>
              <span class="entity-detail-content-info-item-value" :title="entityInfo?.entityTypeText.subcategory">{{
                entityInfo?.entityTypeText.subcategory }}</span>
            </div>
            <div class="ellipse item">
              <span class="entity-detail-content-info-item-label">具体型号</span>
              <span class="entity-detail-content-info-item-value" :title="entityInfo?.entityTypeText.specific">{{
                entityInfo?.entityTypeText.specific }}</span>
            </div>
            <div class="ellipse item">
              <span class="entity-detail-content-info-item-label">拓展型号</span>
              <span class="entity-detail-content-info-item-value" :title="entityInfo?.entityTypeText.extra">{{
                entityInfo?.entityTypeText.extra }}</span>
            </div>
          </el-space>
        </el-col>
      </el-row>

      <div class="entity-detail-content-img" v-if="!isEmpty(entityInfo?.entity.threePath)">
        <!-- 缩略图和进度条 -->
        <div v-if="modelLoading" class="model-loading-container">
          <img v-if="showThumbnail && thumbnailUrl" :src="`/model-api${thumbnailUrl}`" class="model-thumbnail" />
          <div class="model-progress">
            <el-progress :percentage="modelLoadingProgress" :format="percent => `${percent}%`" :stroke-width="6"
              status="success" />
            <div class="model-progress-text">正在加载模型...</div>
          </div>
        </div>
        <div ref="three3DRef" />
      </div>

      <div class="entity-detail-content-footer top">
        <!-- <el-link class="entity-detail-content-footer-text" :underline="false" @click="handleBack">
          <el-icon><Back /></el-icon>
        </el-link> -->
        <div class="edcfi-add-btn" @click="handleAddModel">
          添加模型
        </div>
        <div class="edcfi-model-wrapper" ref="scrollBox" @mousewheel="handleScroll">
          <div class="edcfi-model">
            <div class="edcfi-model-item" :class="modelId === item.id ? 'selected' : ''" v-for="item in modelItems"
              :key="item.id" @click="handleViewModel(item)">
              <span class="model-item-remove" title="删除模型" @click.stop="handleDeleteModel(item)"><el-icon>
                  <Delete />
                </el-icon></span>
              <img v-if="modelId === item.id" src="@@/assets/images/entity/model-item-selected.png" class="emi-img">
              <img v-else src="@@/assets/images/entity/model-item.png" class="emi-img">
              <span class="edcfi-model-item-text ellipse" :title="item.label">
                {{ item.label }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <EditBasicInfo ref="editBasicInfoRef" :id="currentId" :visible="basicVisible" @close-dialog="closeDialog" />
      <EditModel ref="editModelRef" :id="modelId" :visible="modelVisible" :dialog-type="modelDialogType"
        @close-dialog="modelCloseDialog" />
      <fileList ref="editModelRef" :id="modelId" :visible="fileVisible" :file-data="fileData"
        @close-dialog="fileCloseDialog"></fileList>
    </div>
  </div>
</template>
<style lang="scss" scoped>
@import "@@/assets/styles/mixins.scss";

$label-icon-width: 30px;

.top {
  z-index: 999;
}

.edc-sevencode {
  margin-left: 14px;
  margin-right: 100px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;

  & .item {
    border-bottom: 1px solid rgba(176, 171, 171, 0.4);
    padding: 0 10px 14px 0;
    margin-bottom: 24px;
  }
}

@media screen and (max-width: 1920px) {
  .edc-sevencode {
    &>div {
      width: calc(100% / 3);
    }
  }
}

.cpi-header {
  margin-bottom: 24px !important;
}

.item-border {
  width: 100%;
  border-bottom: 1px solid rgba(176, 171, 171, 0.4);
  margin: 0 100px 0 14px;
  padding: 24px 0 14px 0;
  display: flex;

  &:first-child {
    padding-top: 0px;
  }
}

.entity-detail-container {
  padding: 30px 40px;
  width: calc(100%);
  height: calc(100%);
  position: relative;
  overflow: hidden;
  background-image: url(@@/assets/images/entity/model/entity-detail-bg.png);
  background-size: 100% 100%;
  background-position: center;
  background-repeat: no-repeat;
  min-height: 500px;
  overflow-y: auto;

  @extend %scrollbar;
}

.entity-detail-content-img {
  width: calc(100vh);
  height: calc(40vh);
  margin: 0 auto;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); // 使用 transform 进行居中偏移
  border-radius: 4px;
  z-index: 1;

  >div {
    width: 100%;
    height: 100%;
    position: absolute; // 添加绝对定位
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }

  // 模型加载容器样式
  .model-loading-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.05);
    width: 100%;
    height: 100%;
    z-index: 10;

    .model-thumbnail {
      max-width: 80%;
      max-height: 70%;
      object-fit: contain;
      margin-bottom: 20px;
      box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
      border-radius: 4px;
    }

    .model-progress {
      width: 80%;
      max-width: 400px;

      .model-progress-text {
        color: #fff;
        font-size: 14px;
        text-align: center;
        margin-top: 10px;
        text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
      }
    }
  }
}

.entity-detail-content-info-title {
  line-height: 32px;
  font-size: 16px;
  font-weight: 500;
  color: #ffffff;
}

.entity-detail-content-info-item-label {
  padding-left: $label-icon-width;
  line-height: 22px;
  font-size: 14px;
  display: inline-block;
  position: relative;

  &::after {
    content: "：";
    /* 设置伪元素的内容为冒号 */
    display: inline;
    /* 确保伪元素是内联显示的 */
  }

  &::before {
    content: "";
    position: absolute;
    top: 7px;
    left: 0px;
    /* 将伪元素向左移动半个三角形的宽度 */
    border-left: 4px solid transparent;
    border-right: 4px solid transparent;
    border-bottom: 8px solid #ffc42c;
    transform: rotate(90deg);
  }
}

.entity-detail-content-info-item-value-description {
  width: calc(100% - 42px - $label-icon-width);
  font-size: 14px;
  white-space: wrap;
  line-height: 22px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  /* 限制显示的行数 */
  overflow: hidden;
  /* 隐藏超出部分 */
  text-overflow: ellipsis;
  /* 在内容超出时显示省略号 */
}

.ellipse {
  @extend %ellipsis;
}

.entity-detail-content-info-item-value {
  line-height: 22px;
  height: 22px;
  font-size: 14px;
}

.entity-detail-content-footer {
  width: 100%;
  position: absolute;
  bottom: 30px;
  left: 0px;
  padding: 0 40px;
  display: flex;
  height: 104px;
}

.entity-detail-content-footer-text {
  height: 94px;
  margin-right: 43px;
  display: flex;
  align-items: center;

  .el-icon {
    font-size: 28px;
  }
}

.edcfi-add-btn {
  font-size: 14px;
  flex-shrink: 0;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: url(@@/assets/images/entity/add-model-btn.png);
  background-size: 100% 100%;
  width: 94px;
  height: 94px;
}

.edcfi-model-wrapper {
  width: calc(100% - 94px);
  margin-left: 30px;
  padding-bottom: 10px;
  overflow-x: auto;
  overflow-y: hidden;

  @extend %scrollbar;
}

.edcfi-model {
  width: 100%;
  white-space: nowrap;
  display: flex;
  width: 100%;
}

.edcfi-model-item {
  width: 120px;
  height: 94px;
  text-align: center;
  background-image: url(@@/assets/images/entity/model-item-bac.png);
  background-size: 100% 100%;
  box-sizing: border-box;
  flex-shrink: 0;
  cursor: pointer;
  display: flex;
  position: relative;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;

  .model-item-remove {
    position: absolute;
    top: 3px;
    color: #ffffff;
    right: 4px;
    display: none;
    font-size: 18px;
  }

  .emi-img {
    width: 51px;
    height: 54px;
  }

  .edcfi-model-item-text {
    width: calc(100% - 12px);
  }

  &.selected {
    background-image: url(@@/assets/images/entity/model-item-bac-selected.png);
  }

  &:hover {
    background-image: url(@@/assets/images/entity/model-item-bac-selected.png);

    .model-item-remove {
      display: block;
    }
  }
}

.edcfi-model-item+.edcfi-model-item {
  margin-left: 20px;
}

.file-list {
  cursor: pointer;
  display: flex;
  align-items: center;
  overflow: hidden;
  white-space: nowrap;
  padding: 4px 8px;
  // border: 1px solid rgb(255, 255, 255,.5);
  // border-radius: 2px;
}

.file-name {
  margin-right: 12px;
  white-space: nowrap;
  font-size: 14px;

  &:hover {
    color: rgb(0, 187, 153); // 添加背景色
  }
}

.more {
  cursor: pointer;
  color: #FFF;
  font-size: 20px;
  white-space: nowrap;
}

.popover-content {
  cursor: pointer;

  &:hover {
    color: rgb(0, 187, 153); // 添加背景色
  }
}
</style>
